const { execSync, spawn } = require('child_process');
const path = require('path');
// 输出颜色设置
const RED = '\x1b[0;31m';
const GREEN = '\x1b[0;32m';
const YELLOW = '\x1b[0;33m';
const NC = '\x1b[0m'; // No Color

// 获取当前 Node.js 的版本
const NODE_VERSION = execSync('node -v').toString().trim();

// 获取当前客户端
const CLIENT = process.env.npm_package_name;

// 提取主版本号
const MAJOR_VERSION = NODE_VERSION.split('.')[0].slice(1);

console.log(`当前Node.js版本 ${YELLOW}${NODE_VERSION}${NC}`);
console.log(`当前项目 ${YELLOW}${CLIENT}${NC}`);

const command_continue = () => {
  // Check for pnpm
  if (command_exists('pnpm')) {
    command_build('pnpm');
  } else {
    // Check for yarn
    if (command_exists('yarn')) {
      command_build('yarn');
    } else {
      // Check for npm
      if (command_exists('npm')) {
        command_build('npm');
      } else {
        console.log("当前环境暂未安装 npm、pnpm、yarn 工具，请安装后重新运行脚本");
      }
    }
  }
}

const runCommand = (command, callback) => {
  const [cmd, ...args] = command.split(' ');
  const child = spawn(cmd, args, { stdio: 'inherit', shell: true });

  child.on('close', (code) => {
    if (code === 0) {
      if (callback) callback();
    } else {
      console.error(`${RED}命令 ${command} 执行失败，退出码：${code}${NC}`);
      process.exit(code);
    }
  });
}

const command_build = (tool) => {
  console.log(`使用JavaScript包管理工具 ${YELLOW}${tool}${NC}`);
  // 进入 ../common 目录
  process.chdir(path.resolve(__dirname, './common'));
  console.log(`${YELLOW}进入common目录${NC}`);
  console.log(`${GREEN}正在安装依赖...${NC}`);

  runCommand(`${tool} install`, () => {
    console.log(`${GREEN}正在打包...${NC}`);
    runCommand(`${tool} run build`, () => {
      // 返回 ../项目 目录
      console.log(`${YELLOW}进入${CLIENT}目录${NC}`);
      process.chdir(path.resolve(__dirname, `./${CLIENT}`));
      console.log(`${GREEN}正在安装依赖...${NC}`);
      runCommand(`${tool} install`, () => {
        console.log(`${GREEN}正在启动项目...${NC}`);
        runCommand(`${tool} run lunch`);
      });
    });
  });
}

const command_exists = (command) => {
  try {
    // Use appropriate command for each platform
    const platform = process.platform;
    const checkCommand = platform === 'win32' ? `where ${command}` : `command -v ${command}`;
    execSync(checkCommand);
    return true;
  } catch (error) {
    return false;
  }
}

// 比较版本号
if (parseInt(MAJOR_VERSION) >= 18) {
  command_continue();
} else {
  console.log(`${RED}Node.js版本小于18请更新Node.js版本${NC}`);
  console.log(`建议Node.js版本大于${RED} 18.12.0${NC}`);
}
